package com.uqpsoftware.uqplist;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import com.uqpsoftware.uqplist.tabs.TabListListener;
import com.uqpsoftware.uqplist.tabs.TaskListFragment;

public class ActionBarTabs extends SherlockFragmentActivity {

	// tab components
	private CustomViewPager mViewPager;
	private TabsAdapter mTabsAdapter;
	private Context mContext = this;
	private List<TabList> mAllTabs = new ArrayList<TabList>();
	private List<TaskListFragment> mTabFragments = new ArrayList<TaskListFragment>();

	// tab ID
	private static int sNextTabID = 0;

	// keys
	public static final String FRAGMENT_ID_KEY = "FRAGMENT_ID_KEY";

	// persistence and tracking
	private DataPersistence mDataPersistence;
	private GoogleAnalyticsTracker mTracker;
	private final static String UA_NUMBER = "UA-34074720-1";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.i("onCreate actionbartabs", "created!");
		super.onCreate(savedInstanceState);

		mDataPersistence = DataPersistence.get(mContext);

		mViewPager = new CustomViewPager(this);
		mViewPager.setId(R.id.pager);
		setContentView(mViewPager);

		setActionBarOptionsAndModes();

		mTracker = GoogleAnalyticsTracker.getInstance();
		mTracker.startNewSession(UA_NUMBER, 20, this);
		mTracker.setDebug(Util.DEBUG);

		mTabsAdapter = new TabsAdapter(this, mViewPager, mTracker);
		mAllTabs.clear();

		sNextTabID = mDataPersistence.getID();
		populateTabsFromPersistence();

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		mTracker.trackPageView("/OnResume");
	}

	private void populateTabsFromPersistence() {
		mTabsAdapter.setTabCreationFinishedStatus(false);
		Integer selectedTabID = mDataPersistence.getSelectedTab();
		List<TabList> persistedTabs = mDataPersistence.getTabs();
		List<TabList> tabsToBeAdded = Util.sort(persistedTabs);
		tabsToBeAdded = Util.reverse(tabsToBeAdded);
		for (TabList tl : tabsToBeAdded) {
			createTab(tl.getName(), tl.getID());
		}
		if (selectedTabID != null) {
			Util.debugToast(mContext, "selectedTabID: " + selectedTabID);
			Tab currentlySelectedTab = mTabsAdapter.currentlySelectedTab;

			// don't select the tab if it's already the selected tab
			if (mTabsAdapter.getTabID(currentlySelectedTab) != selectedTabID) {
				mTabsAdapter.selectTab(selectedTabID);
			}

		} else {
			Util.debugToast(mContext, "selectedTabID is null");
		}
		mTabsAdapter.setTabCreationFinishedStatus(true);
	}

	TabList getTabListFromID(int ID) {
		for (TabList tl : mAllTabs) {
			if (tl.getID() == ID) {
				return tl;
			}
		}
		return null;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getSupportMenuInflater().inflate(R.menu.activity_main, menu);
		final MenuItem addTab = menu.findItem(R.id.add_tab);
		final MenuItem refreshButton = menu.findItem(R.id.refresh);
		final MenuItem deleteTab = menu.findItem(R.id.deleteTab);
		deleteTab.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {
				deleteTabAlert();
				mTracker.trackEvent("MenuButton", "Click", "AddTab", 0);
				return false;
			}
		});
		refreshButton.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {
				refresh();
				mTracker.trackEvent("MenuButton", "Click", "Refresh", 0);
				return false;
			}

		});
		addTab.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem item) {
				createTabDialog();
				mTracker.trackEvent("MenuButton", "Click", "AddTab", sNextTabID);
				return false;
			}

		});

		return super.onCreateOptionsMenu(menu);
	}

	private void setActionBarOptionsAndModes() {
		ActionBar bar = getSupportActionBar();
		bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		// bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
		bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME,
				ActionBar.DISPLAY_SHOW_HOME);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
						| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		bar.setTitle("UQP");
	}

	protected void deleteTabAlert() {
		Tab tab = mTabsAdapter.currentlySelectedTab;
		if (tab == null) {
			return;
		}
		String tabName = mTabsAdapter.getTabName(tab);
		if (tabName == null) {
			return;
		}
		final AlertDialog newTabDialog = new AlertDialog.Builder(this)
				.setTitle("Delete a List")
				.setMessage(
						"Are you sure you want to delete the list '" + tabName
								+ "'?")
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int ignored) {
						deleteTab();

					}

				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int ignored) {
								// TODO Auto-generated method stub

							}
						}).show();
		newTabDialog.getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

	}

	protected void deleteTab() {
		Integer tabID = mTabsAdapter
				.getTabID(mTabsAdapter.currentlySelectedTab);
		if (tabID == null) {
			return;
		}
		mDataPersistence.unPersistTab(tabID);
		TabList tabListToRemove = null;
		for (TabList tl : mAllTabs) {
			if (tl.getID() == tabID) {
				tabListToRemove = tl;
			}
		}
		TaskListFragment fragmentToRemove = null;
		for (TaskListFragment tlf : mTabFragments) {
			if (tlf.getID() == tabID) {
				fragmentToRemove = tlf;
			}
		}
		mTabFragments.remove(fragmentToRemove);
		mAllTabs.remove(tabListToRemove);

		mTabsAdapter.removeTab(mTabsAdapter.currentlySelectedTab);
	}

	protected void refresh() {
		if (mTabsAdapter.currentlySelectedTab == null) {
			return;
		}
		if (mTabsAdapter.numberOfTabs() == 0) {
			return;
		}
		int currentlySelectedTabID = mTabsAdapter
				.getTabID(mTabsAdapter.currentlySelectedTab);
		for (TaskListFragment tlf : mTabFragments) {
			if (tlf.getID() == currentlySelectedTabID) {
				tlf.refresh();
			}
		}

	}

	TaskListFragment getFragmentWithID(int ID) {
		for (TaskListFragment tlf : mTabFragments) {
			if (tlf.getID() == ID) {
				return tlf;
			}
		}
		return null;
	}

	public void setFragmentToActivity(TaskListFragment tlf, int ID) {
		Util.debugToast(mContext, "adding fragment with id " + ID
				+ ",mTabFragments.size: " + mTabFragments.size());
		TaskListFragment oldFragment = getFragmentWithID(ID);
		if (oldFragment != null) {
			mTabFragments.remove(oldFragment);
		}
		mTabFragments.add(tlf);
	}

	private void createTabDialog() {
		final EditText tabTitleEditText = new EditText(this);

		// setup the dialog
		final AlertDialog newTabDialog = new AlertDialog.Builder(this)
				.setTitle("Create a New List")
				.setMessage("What do you want to call this list?")
				.setView(tabTitleEditText)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int ignored) {
						createTab(tabTitleEditText.getText().toString());

					}

				})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int ignored) {
								// TODO Auto-generated method stub

							}
						}).show();
		newTabDialog.getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

		// setup the textinput
		tabTitleEditText.setFocusable(true);
		tabTitleEditText.setFocusableInTouchMode(true);
		tabTitleEditText.setImeOptions(EditorInfo.IME_ACTION_GO);
		tabTitleEditText.setInputType(InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE);
		tabTitleEditText
				.setOnEditorActionListener(new OnEditorActionListener() {

					@Override
					public boolean onEditorAction(TextView v, int actionId,
							KeyEvent event) {
						createTab(tabTitleEditText.getText().toString());
						newTabDialog.cancel();
						return false;
					}
				});

	}

	private void createTab(String titleOfTab) {
		if (titleOfTab.equals("")) {
			return;
		}
		createTab(titleOfTab, sNextTabID);
		++sNextTabID;
		mDataPersistence.persistActivityID(sNextTabID);
	}

	private void createTab(String titleOfTab, int ID) {
		if (titleOfTab.equals("")) {
			return;
		}
		ActionBar.Tab newTab = getSupportActionBar().newTab();
		newTab.setText(titleOfTab);
		if (Util.DEBUG) {
			newTab.setText(titleOfTab + " " + ID);
		}
		newTab.setTabListener(new TabListListener());
		Bundle argumentsToFragment = new Bundle();
		argumentsToFragment.putString(FRAGMENT_ID_KEY, "" + ID);
		mTabsAdapter.addTab(newTab, TaskListFragment.class,
				argumentsToFragment, ID, titleOfTab);
		getSupportActionBar().selectTab(newTab);
		TabList tabToStore = new TabList(titleOfTab, ID);
		mAllTabs.add(tabToStore);
		mDataPersistence.persistTab(tabToStore);

	}
}